<template>
  <el-dialog v-model="visible" width="90%" :show-close="false" :title="null" :destroy-on-close="true"
    modal-class="roll-pos-image-dialog">
    <div class="dialog-body" v-loading="loading">
      <NewCoilCard title="辊位图" class="dialog-body-card">
        <el-icon class="close-icon" @click="close">
          <Close />
        </el-icon>
        <div class="dialog-body-header">
          <div class="status-wrap"><span>正常: </span><span class="circle"></span></div>
          <div class="status-wrap"><span>未点检: </span><span class="circle not-checked"></span></div>
          <div class="status-wrap"><span>未更换: </span><span class="circle not-replaced"></span></div>
        </div>
        <el-tabs v-if="tabList.length > 1" v-model="activeName" class="demo-tabs">
          <el-tab-pane v-for="item in tabList" :key="item.key" :label="item.label" :name="item.key">
            <div class="svg-wrapper" ref="svgWrapper"></div>
          </el-tab-pane>
        </el-tabs>
        <div v-else class="svg-wrapper" ref="svgWrapper"></div>
      </NewCoilCard>
    </div>
  </el-dialog>
  <RollDetails :param="currentParam" v-model="detailsVisible"></RollDetails>
</template>

<script setup lang="ts">
import { ref, watch, defineProps, defineEmits, defineModel, defineExpose, nextTick } from 'vue'
import { Close } from '@element-plus/icons-vue'
import { getRollStatus } from '/@/api/rollPosImage'
import NewCoilCard from '/@/components/NewCoilCard/NewCoilCard.vue'
import RollDetails from '/@/views/common/RollPosImage/RollDetails.vue';

const visible = defineModel<boolean>('visible', { default: false })
const activeName = defineModel<string>('activeName', { default: '' })

const props = defineProps<{
  rGroup: string
  tabList: Array<{
    key: string
    label: string
    svgUrl: string
  }>
}>()
let pendingChangeList: { line?: string; rGroup?: string; area?: string; pos?: string; rType?: string; [key: string]: any }[] = []
let pendingCheckList: { line?: string; rGroup?: string; area?: string; pos?: string; rType?: string; [key: string]: any }[] = []

const svgWrapper = ref<HTMLElement | HTMLElement[] | null>(null)
const loading = ref<boolean>(false)
const currentParam = ref<{ line: string; rGroup: string, area: string, pos: string, rType:string }>({
  line: '',
  rGroup: '',
  area: '',
  pos: '',
  rType: ''
})
const detailsVisible = ref<boolean>(false)

const loadAndInsertSvg = async () => {
  await nextTick()

  if (!props.tabList.length) return
  loading.value = true
  try {
    if (props.tabList.length === 1) {
      const res = await fetch(props.tabList[0].svgUrl)
      const svgText = await res.text()
      const wrapper = svgWrapper.value as HTMLElement
      wrapper.innerHTML = svgText

      applyHighlight(wrapper)
      bindClickEvents(wrapper)
    } else {
      const index = props.tabList.findIndex(t => t.key === activeName.value)
      if (index === -1) return

      const res = await fetch(props.tabList[index].svgUrl)
      const svgText = await res.text()
      const wrappers = svgWrapper.value as HTMLElement[]
      const wrapper = wrappers[index]
      if (!wrapper) return

      wrapper.innerHTML = svgText
      applyHighlight(wrapper)
      bindClickEvents(wrapper)
    }
  } catch (error) {
    console.log(error);

  } finally {
    loading.value = false
  }

}

const loadData = async () => {
  const { data: { data } } = await getRollStatus({ line: '三分厂', rGroup: props.rGroup });
  pendingChangeList = data?.pendingChangeList || [];
  pendingCheckList = data?.pendingCheckList || [];
}

const applyHighlight = (wrapper: HTMLElement) => {
  const nodes = wrapper.querySelectorAll('circle, ellipse, path')
  nodes.forEach(node => {
    const el = node as HTMLElement
    const line = node.getAttribute('line') || ''
    const rGroup = node.getAttribute('rgroup') || ''
    const area = node.getAttribute('area') || ''
    const pos = node.getAttribute('pos') || ''
    const rType = node.getAttribute('rtype') || ''

    const needChange = pendingChangeList.some(i => i.line === line && i.rGroup === rGroup && i.area === area && i.pos === pos && i.rType === rType)
    const needCheck = pendingCheckList.some(i => i.line === line && i.rGroup === rGroup && i.area === area && i.pos === pos && i.rType === rType)

    if(line && rGroup && area && pos && rType){
      el.style.cursor = 'pointer'
      el.style.fillOpacity = '1'
      el.style.fill = needChange ? '#e11735' : needCheck ? '#ee7616' : '#00FF00'
    }
  })
}

const bindClickEvents = (wrapper: HTMLElement) => {
  const nodes = wrapper.querySelectorAll('circle, ellipse, path')
  nodes.forEach(node => {
    node.addEventListener('click', () => {
      const line = node.getAttribute('line') || ''
      const rGroup = node.getAttribute('rgroup') || ''
      const area = node.getAttribute('area') || ''
      const pos = node.getAttribute('pos') || ''
      const rType = node.getAttribute('rtype') || ''

       if(line && rGroup && area && pos && rType){
        currentParam.value = { line, rGroup, area, pos, rType };
        detailsVisible.value = true
      }
    })
  })
}

const openDialog = async (active = '') => {
  visible.value = true
  activeName.value = active
}

const close = () => {
  visible.value = false

  if (props.tabList.length === 1) {
    (svgWrapper.value as HTMLElement).innerHTML = ''
  } else {
    (svgWrapper.value as HTMLElement[]).forEach(el => {
      el.innerHTML = ''
    })
  }
}

watch(visible, async (val) => {
  if (val) {
    try {
      loading.value = true
      await loadData()
      await loadAndInsertSvg()
    } catch (error) {
      console.log(error);
    } finally {
      loading.value = false
    }
  }
})

watch(activeName, () => {
  if (visible.value && props.tabList.length > 1) {
    loadAndInsertSvg()
  }
})

defineExpose({
  openDialog
})

</script>
<style lang="scss" scoped>
.dialog-body {
  background-color: rgba(28, 58, 99, 0.7);
  :deep(.el-loading-mask){
      background-color: rgba(0,0,0,0.4)
  }
  .dialog-body-card {
    position: relative;

    .close-icon {
      position: absolute;
      right: 14px;
      top: 0.9vh;
      cursor: pointer;
      color: #fff;
      font-size: 1.7vh;
    }
  }

  :deep(.containerContent) {
    flex-direction: column !important;
  }

  .dialog-body-header {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    width: 100%;
    gap: 10px;
    padding: 24px 24px;

    .status-wrap {
      display: flex;
      align-items: center;
      gap: 10px;

      span {
        margin-right: 5px;
        color: #fff;
      }

      .circle {
        width: 14px;
        height: 14px;
        border-radius: 50%;
        background-color: #00FF00;

        &.not-checked {
          background-color: #ee7616;
        }

        &.not-replaced {
          background-color: #e11735;
        }
      }
    }
  }

  .el-tabs {
    :deep(.el-tabs__header) {
      .el-tabs__nav-wrap::after {
        content: none;
      }

      .el-tabs__item {
        color: #fff;

        &:nth-child(2) {
          padding-left: 24px;
        }
      }
    }
  }

  .svg-wrapper {
    width: 100%;
    padding: 14px;
    min-height: 500px;
    max-height: 65vh;
    overflow: auto;
    display: flex;
    justify-content: center;
    align-items: center;
    object-fit: contain;
    scrollbar-width: none;
    -ms-overflow-style: none;

    &::-webkit-scrollbar {
        display: none;
    }

    :deep(svg) {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
